<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true">
        <!--<el-form-item>
            <el-button type="primary" icon="el-icon-s-data"  @click="count">统计</el-button>
        </el-form-item>-->
    </el-form>

    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-download"  @click="exportExcel">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-printer"  @click="print">打印</el-button>
      </el-col>
    </el-row>

    <div style="width: 70%; margin: 0 auto;">
      <table class="custom-table">
        <thead>
          <tr class="title">
            <th colspan="15" style="border: 0 !important;">
              <h1 style="font-size: 28px;" class="h1">
                文件格式统计表
              </h1>
            </th>
          </tr>
          <tr class="dates">
            <th colspan="15" style="border: 0 !important;">
              <h3 style="font-size: 20px;" class="h3">
                {{ dates }}
              </h3>
            </th>
          </tr>

        <tr>
          <th rowspan="2">门类</th>

            <th :colspan="typeCount">格式</th>
            <th rowspan="2">合计</th>
        </tr>
        <tr>
            <template v-for="(value, index) in fileType">
                <th>{{ value }}</th>
            </template>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item, index0) in tableData" :key="item.categoryId">
          <td>{{ item.categoryName }}</td>
            <template v-for="(value, index) in fileType">
                <td>
                    {{ getSumType(item.tj, value) }}
                </td>
            </template>
            <td>{{ item.DOCSUM }}</td>
        </tr>
        </tbody>
      </table>
    </div>


    <div style="width: 90%; height: 1000px; margin: 0 auto; ">
      <div id="histogram" ref="chart" class="chart" style="width: 90%; height:1000px;"></div>
    </div>
  </div>
</template>

<script>
import {fileFormat} from "@/api/archive/statistics/fileFormatStatistics/fileFormatStatistics";
import 'echarts-gl';
import * as XLSX from "xlsx";
import * as echarts from "echarts";

export default {
  name: "index",
  data() {
    return {
      queryParams: {
        startTime: undefined,
        endTime: undefined
      },
      date: "",
      dates: "",
      // 统计表格数据
      tableData: [],

        typeCount:0,
        fileType:[],
        chart: null,
        chartData:[],
        dataUrl: '',
    }
  },
  created() {
    const now = new Date();
    const currentYear = now.getFullYear();
    // this.time = currentYear

    const currentMonth = String(now.getMonth() + 1).padStart(2, '0');
    const currentDate = String(now.getDate()).padStart(2, '0');
    this.date = currentYear + "年" + currentMonth + "月" + currentDate + "日"
    this.getList()
  },

  methods: {
    handleStartYearChange() {
      if(this.queryParams.endTime < this.queryParams.startTime) {
        this.queryParams.startTime = this.queryParams.endTime;
      }
    },
    handleEndYearChange() {
      if(this.queryParams.endTime < this.queryParams.startTime) {
        this.queryParams.endTime = this.queryParams.startTime;
      }
      if (!this.queryParams.startTime) {
        this.queryParams.startTime = this.queryParams.endTime;
      }
    },
    // 统计
    count() {
      this.getList()
    },
    getList() {
      this.dates = "制表日期：" + this.date
        fileFormat().then(response=>{
            this.tableData = response.data.gslist[0].categoryList
            this.typeCount=response.data.type.length
            this.fileType=response.data.type
            this.getHistogram()
      })
    },
      getSumType(tjArray, type) {
          // 查找 tjArray 中 doc_file_type 等于 type 的 sumtype 值
          const match = tjArray.find(item => item.DOC_FILE_TYPE === type);
          return match ? match.SUMTYPE : 0; // 如果没有找到匹配项，则返回 0
      },
    // 导出
    exportExcel() {
      const worksheet = XLSX.utils.table_to_sheet(document.querySelector('.custom-table'));
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      console.log(worksheet)
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      this.saveAsExcel(excelBuffer, `文件格式统计_${new Date().getTime()}`);
    },

    saveAsExcel(buffer, filename) {
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${filename}.xlsx`;
      link.click();
    },

    // 打印
    print() {
      $("input").each(function () {
        $(this).attr('value', $(this).val());
      });

      const tableElement = document.querySelector('.custom-table');
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
      const iframeDoc = iframe.contentWindow.document;

      iframeDoc.open();
      iframeDoc.write(`
          <html>
          <head>
<!--            <title>打印表单</title>-->
            <style>
              @media print {
                .h1 {
                  font-size: 28px;
                  text-align: center;
                }

                .h3 {
                  font-size: 20px;
                  text-align: right;
                }

                .table {
                  margin-top: 5px;
                  padding: 1%;
                }
                .custom-table {
                  width: 100%; /* 设置表格宽度为100% */
                  margin: 0 auto;
                  border-collapse: collapse; /* 合并单元格边框 */
                }

                .custom-table th,
                .custom-table td {
                  padding: 8px; /* 设置单元格内边距 */
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:flex-start;
                  opacity:1;
                  color:#000000;
                  letter-spacing:2px;
                  font-family:仿宋;
                  font-size:16px;
                  border: 1px solid #000; /* 设置单元格边框样式 */
                  padding: 8px; /* 设置单元格内边距 */
                  text-align: center; /* 设置单元格文本居中 */
                }

                .title {
                  heigth: 5em;
                  line-height: 5em;
                  text-align: center;
                  padding:5px 5px 5px 5px;
                  align-items:center;
                  justify-content:center;
                  letter-spacing:4px;
                  font-weight:bold;
                  font-family:宋体;
                  font-size:24px;
                  opacity:1;
                  margin: 0 auto;
                  background:rgba(255, 255, 255, 0) !important;
                  border: 0 !important;
                  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
                }

                .dates {
                  text-align: right;
                }
              }
            </style>
          </head>
          <body>
             ${tableElement.outerHTML}
             <br>
             <br>
             <br>
             <img id="chartImg">
            <script>
              window.onload = function() {
                window.print();
                window.close();
              }
            <\/script>
          </body>
          </html>
      `);
      const img = iframeDoc.getElementById('chartImg');
      img.src = this.dataUrl;
      iframeDoc.close();
    },



      getHistogram() {
          // 获取容器元素
          const chartDom = this.$refs.chart;

          // 初始化 ECharts 实例
          this.chart = echarts.init(chartDom, null, {
              renderer: 'canvas' // 使用 canvas 渲染器
          });

            // 创建 x 轴和 y 轴的索引映射
          const xAxisMap = {};
          // const yAxisMap = {};
          const yAxisSet = new Set(); // 使用 Set 存储唯一的 DOC_FILE_TYPE 值
          // 从 tableData 中提取数据
          const data = [];
          this.tableData.forEach(item => {
              if (!xAxisMap[item.categoryName]) {
                  xAxisMap[item.categoryName] = Object.keys(xAxisMap).length;
              }
              item.tj.forEach(element => {
                  yAxisSet.add(element.DOC_FILE_TYPE); // 将 DOC_FILE_TYPE 值添加到 Set 中
              });

          });
          // 将 Set 转换为数组并生成 yAxisMap
          const yAxisArray = Array.from(yAxisSet);
          const yAxisMap = yAxisArray.reduce((acc, doc, index) => {
              acc[doc] = index; // 确保索引从 0 开始
              return acc;
          }, {});
            //填充数据
          this.tableData.forEach(item => {
              item.tj.forEach(element => {
                  //data.push([item.categoryName, element.DOC_FILE_TYPE, 0, parseInt(element.SUMTYPE)]); // [x, y, z, height]
                  if(parseInt(element.SUMTYPE)>0){
                      data.push([xAxisMap[item.categoryName], yAxisMap[element.DOC_FILE_TYPE], parseInt(element.SUMTYPE)]); // [x, y, z, height]
                  }
              });
          });

          // 反向映射，用于 tooltip 显示
          const reverseXAxisMap = {};
          const reverseYAxisMap = {};

          Object.keys(xAxisMap).forEach(key => {
              reverseXAxisMap[xAxisMap[key]] = key;
          });

          Object.keys(yAxisMap).forEach(key => {
              reverseYAxisMap[yAxisMap[key]] = key;
          });

          // 配置 3D 图表选项
          const option = {
              backgroundColor: '#fff',
              title: {
                  text: '文件格式统计'
              },
              tooltip: {
                  formatter: function (params) {
                      const xValue = reverseXAxisMap[params.value[0]];
                      const yValue = reverseYAxisMap[params.value[1]];
                      const zValue = params.value[2];
                      return `X: ${xValue}<br>Y: ${yValue}<br>Z: ${zValue}`;
                  }
              },
              xAxis3D: {
                  type: 'category',
                  name: '档案门类',
                  data: Object.keys(xAxisMap), // 使用实际的 a 值
                  axisLabel: {
                      interval: 0, // 显示所有标签
                      rotate: 45, // 旋转标签以节省空间
                      margin: 15, // 增加标签与轴之间的距离
                      formatter: function (value) {
                          return value; // 显示实际的 a 值
                      }
                  },
                  nameGap: 40, // 名称与轴之间的距离
              },
              yAxis3D: {
                  type: 'category',
                  name: '文件类型',
                  data: Object.keys(yAxisMap), // 使用实际的 doc 值
                  axisLabel: {
                      interval: 0, // 显示所有标签
                      rotate: 45, // 旋转标签以节省空间
                      margin: 5, // 增加标签与轴之间的距离
                      formatter: function (value) {
                          return value; // 显示实际的 doc 值
                      }
                  },
                  nameGap: 20, // 名称与轴之间的距离
              },
              zAxis3D: {
                  type: 'value',
                  name: '文件数量',
                  min: 0,
                  max: 100 // 根据实际数据调整范围
              },
              grid3D: {
                  boxWidth: 110, // X 轴的宽度
                  boxHeight: 50, // Y 轴的高度
                  boxDepth: 60, // Z 轴的深度
                  viewControl: {
                      projection: 'orthographic',
                      distance: 150, // 视角距离
                      alpha: 45, // 俯仰角
                      beta: 30 // 方位角
                  }

              },
              series: [
                  {
                      type: 'bar3D', // 使用 bar3D 类型
                      coordinateSystem: 'cartesian3D',
                      name: '',
                      data: data,
                      itemStyle: {
                          color: function (params) {
                              // 根据索引返回不同的颜色
                              //var colors = ['#e74c3c', '#2ecc71', '#3498db', '#f1c40f', '#e67e22'];
                              var colors = ['#FF6B6B', '#FFD166', '#06D6A0', '#118AB2', '#EF476F'];
                              return colors[params.dataIndex % colors.length];
                          }
                      },
                      shading: 'lambert', // 使用 Lambert 阴影效果
                      label: {
                          show: false // 可以根据需要显示或隐藏标签
                      },
                      barSize: [3,3,3]//柱子尺寸
                  }
              ],


          };

          // 设置图表配置
          this.chart.setOption(option);
          this.chart.on('finished', () => {
            this.dataUrl = this.chart.getDataURL();
          });
      }
  }
}
</script>

<style lang="scss" scoped>
.h1 {
  font-size: 28px;
  text-align: center;
}

.h3 {
  font-size: 20px;
  text-align: right;
}

.table {
  margin-top: 5px;
  padding: 1%;
}
.custom-table {
   width: 100%; /* 设置表格宽度为100% */
   margin: 0 auto;
   border-collapse: collapse; /* 合并单元格边框 */
 }

.custom-table th,
.custom-table td {
  padding: 8px; /* 设置单元格内边距 */
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:flex-start;
  opacity:1;
  color:#000000;
  letter-spacing:2px;
  font-family:仿宋;
  font-size:16px;
  border: 1px solid #000; /* 设置单元格边框样式 */
  padding: 8px; /* 设置单元格内边距 */
  text-align: center; /* 设置单元格文本居中 */
}

.title {
  heigth: 5em;
  line-height: 5em;
  text-align: center;
  padding:5px 5px 5px 5px;
  align-items:center;
  justify-content:center;
  letter-spacing:4px;
  font-weight:bold;
  font-family:宋体;
  font-size:24px;
  opacity:1;
  margin: 0 auto;
  background:rgba(255, 255, 255, 0) !important;
  border: 0 !important;
  box-shadow:0 0 0 0 rgba(255, 255, 255, 0) !important;
}

.dates {
  text-align: right;
}
</style>
